"use client";
import { Badge, Card, Tabs } from "antd";
import { usePathname, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { queryFriendMessageRequestUsingPost } from "@/api/userRelationshipController";
import styles from "@/app/mood/page.module.css";
import { useSelector } from "react-redux";
import { RootState } from "@/stores";

interface MessageCount {
  commentCount: number;
  thumbCount: number;
  followCount: number;
  systemCount: number;
}

export default function MessageLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const router = useRouter();
  const pathname = usePathname();
  const loginUser = useSelector((state: RootState) => state.loginUser);
  const [counts, setCounts] = useState<MessageCount>({
    commentCount: 0,
    thumbCount: 0,
    followCount: 0,
    systemCount: 0,
  });

  const loadMessageCounts = async () => {
    try {
      // 获取好友请求数量
      const { data: friendRequests } =
        await queryFriendMessageRequestUsingPost();

      // 更新消息数量
      setCounts({
        commentCount: Array.isArray(friendRequests) ? friendRequests.length : 0, // 暂时设为0，等后端接口完成后替换
        thumbCount: Array.isArray(friendRequests) ? friendRequests.length : 0, // 暂时设为0，等后端接口完成后替换
        followCount: Array.isArray(friendRequests) ? friendRequests.length : 0,
        systemCount: Array.isArray(friendRequests) ? friendRequests.length : 0, // 暂时设为0，等后端接口完成后替换
      });

      // 后续添加其他消息数量的获取
      // const { data } = await queryMessageCountUsingGet();
      // if (data) {
      //   setCounts(prev => ({
      //     ...data,
      //     followCount: Array.isArray(friendRequests) ? friendRequests.length : 0
      //   }));
      // }
    } catch (error) {
      console.error("Failed to load message counts:", error);
    }
  };

  useEffect(() => {
    if (loginUser.id) {
      loadMessageCounts();
      // 设置定时器，每3秒执行一次
      const timer = setInterval(loadMessageCounts, 3000);
      // 监听消息更新事件
      const handleMessageUpdate = () => {
        loadMessageCounts();
      };

      window.addEventListener("updateMessage", handleMessageUpdate);

      // 组件卸载时清理定时器和事件监听
      return () => {
        clearInterval(timer);
        window.removeEventListener("updateMessage", handleMessageUpdate);
      };
    }
  }, [loginUser.id]);

  useEffect(() => {
    // 修改事件类型定义，只接收 count
    const handleNotificationCount = (event: CustomEvent<{ count: number }>) => {
      // 不再尝试设置 counts
    };

    window.addEventListener(
      "updateNotificationCount",
      handleNotificationCount as EventListener,
    );

    return () => {
      window.removeEventListener(
        "updateNotificationCount",
        handleNotificationCount as EventListener,
      );
    };
  }, []);

  const items = [
    {
      key: "/my/message/comment",
      label: (
        <Badge count={counts.commentCount} size="small" offset={[10, -5]}>
          <span style={{ fontSize: "16px" }}>评论互动</span>
        </Badge>
      ),
    },
    {
      key: "/my/message/thumb_favour",
      label: (
        <Badge count={counts.thumbCount} size="small" offset={[10, -5]}>
          <span style={{ fontSize: "16px" }}>赞和收藏</span>
        </Badge>
      ),
    },
    {
      key: "/my/message/follow",
      label: (
        <Badge count={counts.followCount} size="small" offset={[10, -3]}>
          <span style={{ fontSize: "16px" }}>新增好友</span>
        </Badge>
      ),
    },
    {
      key: "/my/message/system",
      label: (
        <Badge count={counts.systemCount} size="small" offset={[5, 0]}>
          <span style={{ fontSize: "16px" }}>系统通知</span>
        </Badge>
      ),
    },
  ];

  // 计算总消息数
  const totalCount = Object.values(counts).reduce(
    (sum, count) => sum + count,
    0,
  );

  // 更新导航栏通知数量
  useEffect(() => {
    window.dispatchEvent(
      new CustomEvent("updateNotificationCount", {
        detail: { count: totalCount },
      }),
    );
  }, [totalCount]);

  return (
    <div className={styles.container}>
      <div className={styles.content}>
        <div className={styles.mainContent}>
          <Card
            /*  style={{
                  // marginTop: "30px",
                  marginBottom: "24px",
                  width: "1000px",
                  // marginLeft: "120px",
                }}*/
            // 通知卡片里面内容的样式
            bodyStyle={{
              padding: "22px 24px",
            }}
          >
            <Tabs
              activeKey={pathname}
              items={items}
              onChange={(key) => {
                router.push(key);
              }}
              style={{
                marginBottom: "16px",
              }}
            />
            {children}
          </Card>
        </div>
      </div>
    </div>
  );
}